package com.example.myapplication;

import static com.example.myapplication.CRC16Modbus.crc16Modbus;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Handler;
import android.os.Looper;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import androidx.core.content.ContextCompat;
import com.cdxzwk.serial.SerialPortHelper;
import com.cdxzwk.serial.listener.OnOpenSerialPortListener;
import com.cdxzwk.serial.listener.OnSerialPortDataListener;
import com.cdxzwk.serial.utils.DataUtils;
import com.google.mediapipe.tasks.vision.core.RunningMode;
import com.google.mediapipe.tasks.vision.handlandmarker.HandLandmarkerResult;
import com.google.mediapipe.tasks.components.containers.NormalizedLandmark;
import com.lztek.toolkit.Lztek;

import java.io.File;
import java.util.List;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

public class OverlayView extends View {
    //2024/9/3
    //设置sharedPreferences控制状态
    //完成查询，自动上传模式设置
    //完成自动上传模式逻辑，自动模式下200ms更新一次数据并上传
    private static final String TAG = "OverlayView";
    private HandLandmarkerResult results;
    private boolean flag =false;
    private Paint linePaint;
    private Paint textPaint;
    private Timer timer;
    private TimerTask timerTask;
    private String lastSentData = "";
    private String queryData = "";
    private float scaleFactor = 1f;
    private int imageWidth = 1;
    private int imageHeight = 1;
    private float yCoordinateOfLabelZero;
    private float yCoordinateOfLabelTen;
    private float yCoordinateOfLabelTwenty;
    private float yCoordinateOfLabelThirty;
    private float yCoordinateOfLabelForty;
    private float yCoordinateOfLabelFifty;
    private float yCoordinateOfLabelSixty;
    private SerialPortHelper serialPortHelper;
    private SitReachView sitReachView;
    private SharedPreferences sharedPreferences;
    private static final String SHARED_PREFS_NAME = "device_prefs";
    private static final String DEVICE_MODE_KEY = "device_mode";
    private static final String MODE_AUTO = "auto";
    private static final String MODE_QUERY = "query";
    private Lztek lztek;

    //sharedPreference，存储六条线的位置
    //判定那只手的指尖在最前面，就画那只手的数据

    private void startSerialSendTimer() {

        timer = new Timer();
        timerTask = new TimerTask() {
            @Override
            public void run() {
                // 控制串口发送
                if (!lastSentData.isEmpty()) {
                    serialPortHelper.sendTxt(lastSentData);
                    Log.d("serialAuto-final", "Sent: " + lastSentData);
                }
            }
        };
        // 启动定时任务，每200毫秒执行一次
        timer.schedule(timerTask, 0, 200);
    }

    private void querySerialDataSent() {
        //备用函数 数据查询发送
    }

    private void initSharedPreferences(Context context) {
        sharedPreferences = context.getSharedPreferences(SHARED_PREFS_NAME, Context.MODE_PRIVATE);
    }

    private void setDeviceMode(String mode) {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(DEVICE_MODE_KEY, mode);
        editor.apply();
    }

    private String getDeviceMode() {
        return sharedPreferences.getString(DEVICE_MODE_KEY, MODE_AUTO);
    }

    public void setSitReachView(SitReachView sitReachView) {
        this.sitReachView = sitReachView;
    }

    public void setYCoordinateOfLabelZero(float yCoordinate) {
        this.yCoordinateOfLabelZero = yCoordinate;
    }

    public void setYCoordinateOfLabelTen(float yCoordinateOfLabelTen) {
        this.yCoordinateOfLabelTen = yCoordinateOfLabelTen;
    }

    public void setYCoordinateOfLabelTwenty(float yCoordinateOfLabelTwenty) {
        this.yCoordinateOfLabelTwenty = yCoordinateOfLabelTwenty;
    }

    public void setYCoordinateOfLabelThirty(float yCoordinateOfLabelThirty) {
        this.yCoordinateOfLabelThirty = yCoordinateOfLabelThirty;
    }

    public void setYCoordinateOfLabelForty(float yCoordinateOfLabelForty) {
        this.yCoordinateOfLabelForty = yCoordinateOfLabelForty;
    }

    public void setYCoordinateOfLabelFifty(float yCoordinateOfLabelFifty) {
        this.yCoordinateOfLabelFifty = yCoordinateOfLabelFifty;
    }

    public void setYCoordinateOfLabelSixty(float yCoordinateOfLabelSixty) {
        this.yCoordinateOfLabelSixty = yCoordinateOfLabelSixty;
    }

    public OverlayView(Context context, AttributeSet attrs) {
        super(context, attrs);
        lztek = Lztek.create(this.getContext());
        initPaints(context);
        initSerialPort();
        initSharedPreferences(context);
        initDataListener();
    }

    public static String bytesToHexString(byte[] src, int size) {
        if (src == null || size <= 0 || size > src.length) {
            return null;
        }

        StringBuilder ret = new StringBuilder();
        for (int i = 0; i < size; i++) {
            String hex = Integer.toHexString(src[i] & 0xFF);
            if (hex.length() < 2) {
                hex = "0" + hex;
            }
            ret.append(hex);
        }
        return ret.toString().toUpperCase(Locale.US);
    }

    private void initSerialPort() {

        serialPortHelper = SerialPortHelper.getInstance();
        File device = new File("/dev/ttyS2");
        int baudRate = 9600;
        OnOpenSerialPortListener onOpenSerialPortListener = new OnOpenSerialPortListener() {
            @Override
            public void onSuccess(File device) {
                Log.d("串口0", "串口ttyS2开启成功: " + device.getPath());
            }

            @Override
            public void onFail(File device, Status status) {
                Log.e("SerialPortHelper", "串口开启失败: " + device.getPath() + " Status: " + status);
            }
        };
        serialPortHelper.open(device, baudRate, onOpenSerialPortListener);
    }

    private void initDataListener(){
        /**
         * 2024/9/5
         * 设置数据监听模式
         */
        Log.d("串口0", "initDataListener: 初始串口监听");
        serialPortHelper.setOnSerialPortDataListener(new OnSerialPortDataListener() {
            //字节转十六进制，监听命令
            @Override
            public void onDataReceived(byte[] bytes) {
                String deviceMode = getDeviceMode();
                String receivedData = DataUtils.bytesToHexString(bytes,bytes.length);
                Log.d("串口0", "onDataReceived: 成功打开数据监听"+receivedData);
                if (receivedData.equals("010600060001A80B")){
                    setGpioHighFor20Seconds();
                    setDeviceMode(MODE_QUERY);
                    Log.d("串口0", "成功监听到查询命令，设置为查询模式: "+receivedData);
                    Log.d("串口0", "MODE: "+deviceMode);
                    flag = true;
                    Log.d("串口0", "询问模式下，监听FLAG值为: "+ flag+"————当前是正常状态");

                }
                else if (receivedData.equals("010300000001840A")) {
                    setGpioHighFor20Seconds();
                    setDeviceMode(MODE_AUTO);
                    Log.d("串口0", "成功监听到自动上传命令，设置为自动上传模式: "+receivedData);
                    Log.d("串口0", "MODE: "+deviceMode);
                    flag=false;
                    Log.d("串口0", "上传模式下，监听FLAG值为: "+ flag+"————当前是正常状态");

                }
                else {
                    Log.d("串口0", "监听失败!请检查串口数据发送格式或连接状态 ");
                }
            }
            @Override
            public void onDataSent(byte[] data) {
                System.out.println("进入onDataSent，状态异常");
            }
        });
    }

    private void initPaints(Context context) {

        linePaint = new Paint();
        linePaint.setColor(ContextCompat.getColor(context, R.color.teal_200));
        linePaint.setStrokeWidth(10f);
        linePaint.setStyle(Paint.Style.STROKE);

        textPaint = new Paint();
        textPaint.setColor(Color.BLACK);
        textPaint.setTextSize(30f);
        textPaint.setTextAlign(Paint.Align.LEFT);

    }

    public void setResults(HandLandmarkerResult results, int imageHeight, int imageWidth, RunningMode runningMode) {
        this.results = results;
        this.imageHeight = imageHeight;
        this.imageWidth = imageWidth;
        this.scaleFactor = (runningMode == RunningMode.LIVE_STREAM) ?
                Math.max((float) getWidth() / imageWidth, (float) getHeight() / imageHeight) :
                Math.min((float) getWidth() / imageWidth, (float) getHeight() / imageHeight);
        invalidate();
    }

    private String addSpacesEveryTwoChars(String input) {
        StringBuilder spacedString = new StringBuilder();
        for (int i = 0; i < input.length(); i += 2) {
            spacedString.append(input, i, Math.min(i + 2, input.length())).append(" ");
        }
        return spacedString.toString().trim();
    }

    public void setGpioHighFor20Seconds() {
        if (lztek != null) {
            // 设置 GPIO 88 为高电平
            lztek.gpioEnable(88);
            lztek.setGpioValue(88, 1);

            new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
                @Override
                public void run() {
                    lztek.setGpioValue(88, 0);
                    Log.d("OverlayView", "GPIO 88 set to low after 20 seconds");
                }
            }, 20000);
        } else {
            Log.d("OverlayView", "Lztek is null, cannot set GPIO value");
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        String deviceMode = getDeviceMode();

        if (MODE_QUERY.equals(deviceMode) && flag){
            super.onDraw(canvas);
            if (sitReachView != null) {

                yCoordinateOfLabelZero = sitReachView.getYCoordinateOfLabelZero();
                yCoordinateOfLabelTen = sitReachView.getYCoordinateOfLabelTen();
                yCoordinateOfLabelTwenty = sitReachView.getYCoordinateOfLabelTwenty();
                yCoordinateOfLabelThirty = sitReachView.getYCoordinateOfLabelThirty();
                yCoordinateOfLabelForty = sitReachView.getYCoordinateOfLabelForty();
                yCoordinateOfLabelFifty = sitReachView.getYCoordinateOfLabelFifty();
                yCoordinateOfLabelSixty = sitReachView.getYCoordinateOfLabelSixty();

            }

            if (results != null && !results.landmarks().isEmpty()) {
                List<NormalizedLandmark> leftHandLandmarks = results.landmarks().size() > 0 ? results.landmarks().get(0) : null;
                List<NormalizedLandmark> rightHandLandmarks = results.landmarks().size() > 1 ? results.landmarks().get(1) : null;

                if (leftHandLandmarks != null && rightHandLandmarks != null) {
                    NormalizedLandmark leftMiddleFingerTip = leftHandLandmarks.size() > 12 ? leftHandLandmarks.get(12) : null;
                    NormalizedLandmark rightMiddleFingerTip = rightHandLandmarks.size() > 12 ? rightHandLandmarks.get(12) : null;

                    Log.d(TAG, "maxValue: ");
                    if (leftMiddleFingerTip != null && rightMiddleFingerTip != null) {
                        // 竖屏坐标计算，修正y轴
                        float yLeft = leftMiddleFingerTip.y() * imageHeight * scaleFactor-10;
                        float xLeft =  leftMiddleFingerTip.x() * imageWidth * scaleFactor - 0;
                        float yRight = rightMiddleFingerTip.y() * imageHeight * scaleFactor-10;
                        float xRight =  rightMiddleFingerTip.x() * imageWidth * scaleFactor - 0;

                        float normalizedYLeft = normalize(yLeft, yCoordinateOfLabelZero, yCoordinateOfLabelTen, yCoordinateOfLabelTwenty, yCoordinateOfLabelThirty, yCoordinateOfLabelForty, yCoordinateOfLabelFifty, yCoordinateOfLabelSixty);
                        float normalizedYRight = normalize(yRight, yCoordinateOfLabelZero, yCoordinateOfLabelTen, yCoordinateOfLabelTwenty, yCoordinateOfLabelThirty, yCoordinateOfLabelForty, yCoordinateOfLabelFifty, yCoordinateOfLabelSixty);

                        // 保留一位小数并四舍五入
                        float roundedYLeft = Math.round(normalizedYLeft * 10) / 10.0f;
                        float roundedYRight = Math.round(normalizedYRight * 10) / 10.0f;

                        // 将保留一位小数后的值转换为整数，乘以10后再取整
                        int intLeft = Math.round(roundedYLeft * 10);
                        Log.d(TAG, "规范化后的左: " + intLeft);
                        int intRight = Math.round(roundedYRight * 10);
                        Log.d(TAG, "规范化后的右: " + intRight);

                        // 定义浮点数
                        float divisor = 0.024533249168467f;

                        // 计算结果
                        float resultLeft = intLeft / divisor;
                        float resultRight = intRight / divisor;

                        // 打印结果
                        Log.d(TAG, "左除以0.024533249168467的结果: " + resultLeft);
                        Log.d(TAG, "右除以0.024533249168467的结果: " + resultRight);

                        // 先将浮点数转换为 long 类型
                        long longLeft = (long) resultLeft;
                        long longRight = (long) resultRight;
                        // 选择绘制前面的手的指尖切线，并拼接数据
                        if (yLeft < yRight) {

                            Log.d(TAG, "左手指尖: " + normalizedYLeft);
                            drawFingerTipLine(canvas, xLeft, yLeft, "左手", normalizedYLeft);

                            // 将 intLeft 转换为四位的十六进制字符串，保证结果有4位
                            String hexLeft = String.format("%08X", longLeft);

                            // 将四位十六进制字符串自动分割为每个字节，确保有空格
                            String leftBytes = addSpacesEveryTwoChars(hexLeft);

                            // 数据前缀 "01 03 02" 是固定的
                            String dataPrefix = "01 03 02 ";

                            // 拼接数据位部分
                            String dataToSend = dataPrefix + leftBytes;

                            // 计算CRC16/MODBUS校验值（传入的数据要去除空格）
                            String crc = crc16Modbus(dataToSend.replace(" ", ""));

                            // 将 CRC 结果自动分割为每个字节，确保有空格
                            String crcBytes = addSpacesEveryTwoChars(crc);

                            // 最终拼接发送的数据
                            String queryData = dataToSend + " " + crcBytes;
                            Log.d("Serial", "query-left: " + queryData);

                            // 发送拼接好的数据
                            serialPortHelper.sendHex(queryData);

                            Log.d("Serial", "query-成功发送左手数据 "+queryData);

                            setDeviceMode(MODE_AUTO);


                        } else {
                            //setGpioHighFor20Seconds();
                            Log.d(TAG, "右手指尖: " + normalizedYRight);
                            drawFingerTipLine(canvas, xRight, yRight, "右手", normalizedYRight);

                            // 将 intRight 转换为四位的十六进制字符串，保证结果有4位
                            String hexRight = String.format("%08X", longRight);

                            // 将四位十六进制字符串自动分割为每个字节，确保有空格
                            String rightBytes = addSpacesEveryTwoChars(hexRight);

                            // 数据前缀 "01 03 02" 是固定的
                            String dataPrefix = "01 03 04 ";

                            // 拼接数据位部分
                            String dataToSend = dataPrefix + rightBytes;

                            // 计算CRC16/MODBUS校验值（传入的数据要去除空格）
                            String crc = crc16Modbus(dataToSend.replace(" ", ""));

                            // 将 CRC 结果自动分割为每个字节，确保有空格
                            String crcBytes = addSpacesEveryTwoChars(crc);

                            // 最终拼接发送的数据
                            String queryData = dataToSend + " " + crcBytes;
                            Log.d("Serial", "query-right: " + queryData);
                            //serialPortHelper.sendHex(queryData);
                            // 发送拼接好的数据
                            Log.d("Serial", "query-成功发送右手数据 "+queryData+"查询已经完成");
                            setDeviceMode(MODE_AUTO);

                        }
                        flag = false;
                        Log.d("串口0", "操作完成后的FLAG值为: "+flag);
                        //querySerialSentData();
                    }
                } else if (leftHandLandmarks != null && leftHandLandmarks.size() > 12) {
                    NormalizedLandmark leftMiddleFingerTip = leftHandLandmarks.get(12);

                    float yLeft = leftMiddleFingerTip.y() * imageHeight * scaleFactor-10;
                    float xLeft = leftMiddleFingerTip.x() * imageWidth * scaleFactor - 0;

                    float normalizedYLeft = normalize(yLeft, yCoordinateOfLabelZero, yCoordinateOfLabelTen, yCoordinateOfLabelTwenty, yCoordinateOfLabelThirty, yCoordinateOfLabelForty, yCoordinateOfLabelFifty, yCoordinateOfLabelSixty);
                    drawFingerTipLine(canvas, xLeft, yLeft, "左手", normalizedYLeft);
                } else if (rightHandLandmarks != null && rightHandLandmarks.size() > 12) {
                    NormalizedLandmark rightMiddleFingerTip = rightHandLandmarks.get(12);


                    float yRight = rightMiddleFingerTip.y() * imageHeight * scaleFactor-10;
                    float xRight = rightMiddleFingerTip.x() * imageWidth * scaleFactor - 0;

                    float normalizedYRight = normalize(yRight, yCoordinateOfLabelZero, yCoordinateOfLabelTen, yCoordinateOfLabelTwenty, yCoordinateOfLabelThirty, yCoordinateOfLabelForty, yCoordinateOfLabelFifty, yCoordinateOfLabelSixty);
                    drawFingerTipLine(canvas, xRight, yRight, "右手", normalizedYRight);
                }
            }
        }else if (MODE_AUTO.equals(deviceMode)) {

            super.onDraw(canvas);
            if (sitReachView != null) {

                yCoordinateOfLabelZero = sitReachView.getYCoordinateOfLabelZero();
                yCoordinateOfLabelTen = sitReachView.getYCoordinateOfLabelTen();
                yCoordinateOfLabelTwenty = sitReachView.getYCoordinateOfLabelTwenty();
                yCoordinateOfLabelThirty = sitReachView.getYCoordinateOfLabelThirty();
                yCoordinateOfLabelForty = sitReachView.getYCoordinateOfLabelForty();
                yCoordinateOfLabelFifty = sitReachView.getYCoordinateOfLabelFifty();
                yCoordinateOfLabelSixty = sitReachView.getYCoordinateOfLabelSixty();
//
//                Log.d("AJZ", "0: "+yCoordinateOfLabelZero);
//                Log.d("AJZ", "1: "+yCoordinateOfLabelTen);
//                Log.d("AJZ", "2: "+yCoordinateOfLabelTwenty);
//                Log.d("AJZ", "3: "+yCoordinateOfLabelThirty);
//                Log.d("AJZ", "4: "+yCoordinateOfLabelForty);
//                Log.d("AJZ", "5: "+yCoordinateOfLabelFifty);
//                Log.d("AJZ", "6: "+yCoordinateOfLabelSixty);

            }
            flag = false;
            //Log.d("DEVICE", "MODE: "+deviceMode);
            if (results != null && !results.landmarks().isEmpty()) {
                List<NormalizedLandmark> leftHandLandmarks = results.landmarks().size() > 0 ? results.landmarks().get(0) : null;
                List<NormalizedLandmark> rightHandLandmarks = results.landmarks().size() > 1 ? results.landmarks().get(1) : null;

                if (leftHandLandmarks != null && rightHandLandmarks != null) {
                    NormalizedLandmark leftMiddleFingerTip = leftHandLandmarks.size() > 12 ? leftHandLandmarks.get(12) : null;
                    NormalizedLandmark rightMiddleFingerTip = rightHandLandmarks.size() > 12 ? rightHandLandmarks.get(12) : null;

                    if (leftMiddleFingerTip != null && rightMiddleFingerTip != null) {
                        // 竖屏坐标计算
                        // 处理左手指尖的坐标
                        float yLeft = leftMiddleFingerTip.y() * imageHeight * scaleFactor-10;
                        float xLeft =  leftMiddleFingerTip.x() * imageWidth * scaleFactor - 0;
                        float yRight = rightMiddleFingerTip.y() * imageHeight * scaleFactor-10;
                        float xRight =  rightMiddleFingerTip.x() * imageWidth * scaleFactor - 0;

                        // 标准化
                        float normalizedYLeft = normalize(yLeft, yCoordinateOfLabelZero, yCoordinateOfLabelTen, yCoordinateOfLabelTwenty, yCoordinateOfLabelThirty, yCoordinateOfLabelForty, yCoordinateOfLabelFifty, yCoordinateOfLabelSixty);
                        float normalizedYRight = normalize(yRight, yCoordinateOfLabelZero, yCoordinateOfLabelTen, yCoordinateOfLabelTwenty, yCoordinateOfLabelThirty, yCoordinateOfLabelForty, yCoordinateOfLabelFifty, yCoordinateOfLabelSixty);

                        Log.d(TAG, "左手指尖: " + normalizedYLeft);
                        Log.d(TAG, "右手指尖: " + normalizedYRight);

                        // 矫正200
                        // 保留一位小数并四舍五入
                        float roundedYLeft = Math.round(normalizedYLeft * 10) / 10.0f;
                        float roundedYRight = Math.round(normalizedYRight * 10) / 10.0f;

                        // 将保留一位小数后的值转换为整数，乘以10后再取整
                        int intLeft = Math.round(roundedYLeft * 10);
                        Log.d(TAG, "规范化后的左: " + intLeft);
                        int intRight = Math.round(roundedYRight * 10);
                        Log.d(TAG, "规范化后的右: " + intRight);

                        // 定义浮点数
                        float divisor = 0.024533249168467f;

                        // 计算结果
                        float resultLeft = intLeft / divisor;
                        float resultRight = intRight / divisor;

                        // 打印结果
                        Log.d(TAG, "左除以0.024533249168467的结果: " + resultLeft);
                        Log.d(TAG, "右除以0.024533249168467的结果: " + resultRight);

                        // 先将浮点数转换为 long 类型
                        long longLeft = (long) resultLeft;

                        if (yLeft < yRight) {

                            Log.d(TAG, "左手指尖: " + normalizedYLeft);
                            drawFingerTipLine(canvas, xLeft, yLeft, "右手", normalizedYLeft);

                            // 将 intLeft 转换为四位的十六进制字符串，保证结果有4位
                            String hexLeft = String.format("%08X", longLeft);
                            Log.d("Sixteen", "左除以0.024533249168467的结果: " + resultLeft);
                            // 将四位十六进制字符串自动分割为每个字节，确保有空格
                            String leftBytes = addSpacesEveryTwoChars(hexLeft);

                            // 数据前缀 "01 03 02" 是固定的
                            String dataPrefix = "01 03 04 ";

                            // 拼接数据位部分
                            String dataToSend = dataPrefix + leftBytes;

                            // 计算CRC16/MODBUS校验值（传入的数据要去除空格）
                            String crc = crc16Modbus(dataToSend.replace(" ", ""));

                            // 将 CRC 结果自动分割为每个字节，确保有空格
                            String crcBytes = addSpacesEveryTwoChars(crc);

                            // 最终拼接发送的数据
                            String queryData = dataToSend + " " + crcBytes;
                            Log.d("Serial", "auto-left: " + queryData);

                            // 发送拼接好的数据
                            serialPortHelper.sendHex(queryData);
                            Log.d("Serial", "auto-成功发送左手数据 "+queryData);
//                            setDeviceMode(MODE_QUERY);

                        } else {

                            long longRight = (long) resultRight;

                            Log.d(TAG, "右手指尖: " + normalizedYRight);
                            drawFingerTipLine(canvas, xRight, yRight, "左手", normalizedYRight);

                            // 将 intRight 转换为四位的十六进制字符串，保证结果有4位
                            String hexRight = String.format("%08X", longRight);
                            Log.d("Sixteen", "右除以0.024533249168467的结果: " + resultRight);
                            // 将四位十六进制字符串自动分割为每个字节，确保有空格
                            String rightBytes = addSpacesEveryTwoChars(hexRight);

                            // 数据前缀 "01 03 02" 是固定的
                            String dataPrefix = "01 03 04 ";

                            // 拼接数据位部分
                            String dataToSend = dataPrefix + rightBytes;

                            // 计算CRC16/MODBUS校验值（传入的数据要去除空格）
                            String crc = crc16Modbus(dataToSend.replace(" ", ""));

                            // 将 CRC 结果自动分割为每个字节，确保有空格
                            String crcBytes = addSpacesEveryTwoChars(crc);

                            // 最终拼接发送的数据
                            String queryData = dataToSend + " " + crcBytes;
                            Log.d("Serial", "auto-right: " + queryData);
                            serialPortHelper.sendHex(queryData);
                            // 发送拼接好的数据
                            Log.d("Serial", "auto-成功发送右手数据 "+queryData);
                            //setDeviceMode(MODE_QUERY);
                        }
                        startSerialSendTimer();
                    }

                } else if (leftHandLandmarks != null && leftHandLandmarks.size() > 12) {
                    NormalizedLandmark leftMiddleFingerTip = leftHandLandmarks.get(12);

                    float yLeft = leftMiddleFingerTip.y() * imageHeight * scaleFactor-10;
                    float xLeft = leftMiddleFingerTip.x() * imageWidth * scaleFactor - 0;
                    float normalizedYLeft = normalize(yLeft, yCoordinateOfLabelZero, yCoordinateOfLabelTen, yCoordinateOfLabelTwenty, yCoordinateOfLabelThirty, yCoordinateOfLabelForty, yCoordinateOfLabelFifty, yCoordinateOfLabelSixty);
                    drawFingerTipLine(canvas, xLeft, yLeft, "自动模式，当前是未准备状态，左手", normalizedYLeft);
                    Log.d("ts", "调试左手数据: "+normalizedYLeft);
                } else if (rightHandLandmarks != null && rightHandLandmarks.size() > 10) {
                    NormalizedLandmark rightMiddleFingerTip = rightHandLandmarks.get(12);



                    float yRight = rightMiddleFingerTip.y() * imageHeight * scaleFactor-10;
                    float xRight = rightMiddleFingerTip.x() * imageWidth * scaleFactor - 0;

                    float normalizedYRight = normalize(yRight, yCoordinateOfLabelZero, yCoordinateOfLabelTen, yCoordinateOfLabelTwenty, yCoordinateOfLabelThirty, yCoordinateOfLabelForty, yCoordinateOfLabelFifty, yCoordinateOfLabelSixty);
                    drawFingerTipLine(canvas, xRight, yRight, "自动模式，当前是未准备状态，右手", normalizedYRight);
                }
            }
        }
    }

    private void drawFingerTipLine(Canvas canvas, float x, float y, String hand, float normalizedY) {
        float lineLength = 2500f;
        canvas.drawLine(x - lineLength / 2, y, x + lineLength / 2, y, linePaint);
        linePaint.setStrokeWidth(2.0f);
        String yCoordinateText = hand + "当前指尖Y坐标: " + String.format("%.1f", normalizedY);
        float textX = 10;
        float textY = hand.equals("左手") ? canvas.getHeight() - 60 : canvas.getHeight() - 30;
        textPaint.setColor(Color.WHITE);
        canvas.drawText(yCoordinateText, textX, textY, textPaint);
    }

    private float normalize(float y, float y0, float y10, float y20, float y30, float y40, float y50, float y60) {
        if (y <= y0 && y >= y10) {
            return interpolate(y, y0, y10, 0, 10);
        } else if (y < y10 && y >= y20) {
            return interpolate(y, y10, y20, 10, 20);
        } else if (y < y20 && y >= y30) {
            return interpolate(y, y20, y30, 20, 30);
        } else if (y < y30 && y >= y40) {
            return interpolate(y, y30, y40, 30, 40);
        } else if (y < y40 && y >= y50) {
            return interpolate(y, y40, y50, 40, 50);
        } else if (y < y50 && y >= y60) {
            return interpolate(y, y50, y60, 50, 60);
        }
        return -1;
    }

    private float interpolate(float y, float yStart, float yEnd, float labelStart, float labelEnd) {
        return labelStart + (y - yStart) * (labelEnd - labelStart) / (yEnd - yStart);
    }


}
